const rbacPlugin = require('hapi-rbac');

exports.plugin = {
  name: 'rbacPlugin',
  register: async (server) => {
    await server.register({
      plugin: rbacPlugin,
      options: {
        async policy(req) {
          if (!req.auth.credentials) {
            // 放行文档和静态文件
            return {
              effect: 'permit',
            };
          }

          if (req.auth.credentials.username === 'root') {
            // 如果是超级管理员，所有的资源开放
            return {
              effect: 'permit',
            };
          }

          // 动态的给资源设置策略
          const { path, method } = req.route;
          const pol = await req.policiesModel.getPolicyByMethodAndPath({ path, method });
          if (pol.length === 0) {
            return {
              effect: 'deny',
            };
          }
          if (pol) {
            const credentialsGroup = pol.map((el) => ({
              'credentials:group': el.group,
            }));
            return {
              resource: { path, method },
              target: credentialsGroup,
              effect: 'permit',
            };
          }
          return {
            effect: 'deny',
          };
        },
      },
    });
  },
};
